package org.duang.kit;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.duang.http.base.HttpClient;
import org.duang.http.base.HttpRes;
import org.duang.http.common.ResponseMessage;
import org.duang.http.core.enums.HttpMethod;
import org.duang.http.core.inter.AsyncCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpClient 请求工具类
 * @author laotang
 */
public class HttpKit {
	
	private static Logger logger = LoggerFactory.getLogger(HttpKit.class);
	
	private static Map<String,Object> params;
	private String url;
	private boolean isSecurity;
	private InputStream content;
	private static HttpKit httpKit;
	
	public final static String TOKENID_FIELD = "tokenid";
	
	public static HttpKit duang(){
		if(ToolsKit.isEmpty(httpKit)){
			httpKit = new HttpKit();
		}
		if(ToolsKit.isEmpty(params)){
			params = new HashMap<String,Object>();
		} else {
			params.clear();
		}
		return httpKit;
	}
	
	public HttpKit setTokenId(String value) {
		params.put(TOKENID_FIELD, value);
		return this;
	}
	
	public HttpKit param(String key, Object value) {
		if(value instanceof java.io.File){
			throw new IllegalArgumentException("duang httpclient is not accepted for file param submit!");
		}
		if(!key.equalsIgnoreCase(TOKENID_FIELD)){
			params.put(key, value);
		}
		return this;
	}
	
	public HttpKit body(String value) {
		content = ToolsKit.string2InputStream(value, ToolsKit.CHARSET_UTF_8);
		return this;
	}
	
	public HttpKit url(String url) {
		this.url = url;
		return this;
	}
	
	public HttpKit security(boolean isSecurity) {
		this.isSecurity = isSecurity;
		return this;
	}
	
	public HttpRes get() {
		return request(HttpMethod.GET, null);
	}
	
	public HttpRes post() {
		return request(HttpMethod.POST, null);
	}
	
	public void get(AsyncCallback<ResponseMessage> callback) {
		request(HttpMethod.GET, callback);
	}
	
	public void post(AsyncCallback<ResponseMessage> callback) {
		request(HttpMethod.POST, callback);
	}

	private HttpRes request(HttpMethod method, AsyncCallback<ResponseMessage> callback) {
		try{
			HttpClient client = new HttpClient(method, url, params, content);
			client.setSecurity(isSecurity);	
			if(ToolsKit.isEmpty(callback)){
				return client.send();
			} else {
				client.send(callback);
			}
		} catch ( Exception e ){
			logger.warn(e.getMessage(), e);
		}
		return null;
	}
}
